<template
  ><!---->
  <div id="test">
    <search-table
      :columns="listCol" 
      :data="retData.list"
      :total="retData.total"
      :page.sync="queryParams.pageIndex"
      :size.sync="queryParams.pageSize"
      @queryFun="getRankingStatic"
    >
    <template slot="button-group">
      <Button
        type="primary"
        ghost
        :disabled="disabledAllBtn"
        @click="showUploadModal"
        icon="md-options">提交报告</Button>
    </template>
      <template slot="select-group">
        <Select filterable
          v-model="queryParams.teamId"
          placeholder="请选择团队"
          filterable
          clearable
          transfer
          @on-change="getRankingStatic(1)"
        >
          <Option v-for="item in teamList" :value="item.id" :key="item.id" :title="item.name">{{
            item.name
          }}</Option>
        </Select>
        <Select filterable
          v-model="queryParams.company"
          placeholder="请选择单位"
          filterable
          clearable
          transfer
          @on-change="getRankingStatic(1)"
        >
          <Option v-for="item in companyList" :value="item" :key="item" :title="item">{{
            item
          }}</Option>
        </Select>
        <Select filterable
          v-model="queryParams.target"
          placeholder="请选择目标"
          filterable
          clearable
          transfer
          @on-change="getRankingStatic(1)"
        >
          <Option
            v-for="item in topoTargetData"
            :value="item.id"
            :key="item.id"
            :title="item.name"
            >{{ item.name }}</Option
          >
        </Select>
        <!-- 众测中有攻击方不显示查询了 -->
        <Select filterable
          v-model="queryParams.type"
          filterable
          placeholder="请选择报告类型"
          clearable
          @on-change="getRankingStatic(1)"
          v-if="hwType != 2"
        >
          <Option :value="1">攻击报告</Option>
          <Option :value="2">防御报告</Option>
        </Select>
        <!-- <Select filterable
          transfer
          v-model="queryParams.publicTarget"
          placeholder="是否公共目标"
          filterable
          clearable
          @on-change="getRankingStatic(1)"
        >
          <Option value="1">是</Option>
          <Option value="0">否</Option>
        </Select> -->
        <!-- <Select filterable
                    v-model="queryParams.industry"
                    placeholder="请选择行业"
                    filterable
                    clearable
                    @on-change="getRankingStatic(1)">
                    <Option  v-for="item in industryList" :value="item.dictid"  :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
                </Select> -->
        <!-- <Select filterable
                    v-model="queryParams.attackType"
                    placeholder="请选择攻击类型"
                    filterable
                    clearable
                    @on-change="getRankingStatic(1)">
                    <Option  v-for="item in attackList" :value="item.dictid"  :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
                </Select> -->
        <!-- <Cascader
          :render-format="renderFormat"
          transfer
          :data="extent4DefenseTypesData"
          v-model="queryParams.defenseTypes"
          placeholder="请选择防守类型"
          filterable
          clearable
          @on-change="getRankingStatic(1)"
        ></Cascader> -->
        <!-- <Cascader
          :render-format="renderFormat"
          transfer
          :data="extent4InjuryData"
          v-model="queryParams.attackLevel"
          placeholder="请选择危害程度"
          filterable
          clearable
          @on-change="getRankingStatic(1)"
        ></Cascader> -->
        <Select filterable
          v-model="queryParams.level"
          placeholder="请选择危险等级"
          filterable
          clearable
          @on-change="getRankingStatic(1)"
        >
          <Option value="high">高危</Option>
          <Option value="middle">中危</Option>
          <Option value="low">低危</Option>
        </Select>
        <Select filterable
          v-model="queryParams.isverify"
          placeholder="请选择审核状态"
          filterable
          clearable
          @on-change="getRankingStatic(1)"
        >
          <Option value="1">未审核</Option>
          <Option value="2">审核通过</Option>
          <Option value="3">驳回</Option>
          <Option value="4">挂起</Option>
          <Option value="5">驳回后再提交</Option>
        </Select>
      </template>
    </search-table>
    <!-- <card-list slot="table" :columns="listCol" :data="retData.list"></card-list> -->
    <!-- <table-body :options="initObj"></table-body> -->
    <Modal
      v-model="reportModal"
      :title="modalTitle"
      width="800px"
      :mask-closable="false"
      footer-hide
    >
      <table-body
        :options="reportInitObj"
        v-if="reportModal"
        :hidePage="true"
        noDataText="暂无报告"
      ></table-body>
    </Modal>
    <ReportSubmit ref="submitReportModal" :drillDetail="drillDetail" :taskReportListData="taskList"></ReportSubmit>
    <Modal v-model="reportTreeModal.show" :title="reportTreeModal.title" footer-hide>
      <ReportTree v-if="reportTreeModal.show" :testId="$route.query.id" :company="reportTreeModal.company"></ReportTree>
    </Modal>
  </div>
</template>
<script>
//	import Cookies from 'js-cookie'
import { reportStatis, downloadFile } from '@/api/compitionStatic';
import { reportFileData } from '@/api/referee';
import { allDirection } from '@/api/dict';
import tableBody from './tableListComponent';
import groupMixin from '@/mixin/groupMixin';
import LevelMixin from '@/mixin/levelMixin';
import { getTopoTargetList, queryHWScoreRule, getDeclareCompanyList } from '@/api/drill_compete';
import { getTaskList } from '@/api/drill'
import SearchTable from '@/components/SearchTable/SearchTable';
import ReportSubmit from '@/view/drill_compete/page/hw/upload-submit'
import ReportTree from '@/view/drill_compete/page/statistics/report-tree.vue'
export default {
  name: 'hwTeamRankStatic',
  components: {
    'table-body': tableBody,
    SearchTable,
    ReportSubmit,
    ReportTree
  },
  props: ['sceneId', 'poll', 'drillDetail', 'taskReportListData', 'disabledAllBtn','type'],
  mixins: [groupMixin, LevelMixin],
  data() {
    const d = function(val) {
      this.getRankingStatic(null, null, val);
    }.bind(this);

    return {
      reportTreeModal:{
        show:false,
        title:'单位报告树'
      },
      taskList: [],
      modalData: {
          show: false
      },
      queryParams: {
        teamId: '',
        target: '',
        industry: '',
        attackType: '',
        level: '',
        isverify: '',
        company: '',
        defenseTypes: [],
        attackLevel: [],
        publicTarget: '',
        pageIndex: 1,
        type: '',
        pageSize: 10
      },
      retData: {
        total: 0,
        list: []
      },
      modalTitle: '',
      topoTargetData: [],
      reportModal: false,
      c: false,
      listCol: [
        {
          title: '团队名称',
          key: 'groupName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-left',
          order: 1
        },
        {
          title: '目标名称',
          key: 'targetName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          placement: 'top-left'
        },
        {
          title: '任务名称',
          key: 'taskName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '报告',
          key: 'reportName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        // {
        //   title: '行业',
        //   key: 'industryName',
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   width: 100
        // },
        {
          title: '单位',
          key: 'company',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '攻击类型',
          key: 'attackTypeName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '防守类型',
          key: 'defenseTypeName',
          width: 100,
          tooltip: true
        },
        // {
        //   title: '审核状态', //1提交，2审批通过，3审批驳回，4审批挂起，5驳回后再提交
        //   key: 'status',
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   placement: 'top-right',
        //   render: (h, params) => {
        //     return h(
        //       'span',
        //       params.row.status == 1 ? '提交' : params.row.status == 2 ? '审批通过' : params.row.status == 3 ? '审批驳回' : params.row.status == 4 ? '审批挂起' : '驳回后再提交'
        //     );
        //   }
        // },
        {
          title: '提交人',
          key: 'creatorName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '提交时间',
          key: 'createTime',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '审核状态',
          key: 'status',
          align: 'center',
          ellipsis: true,
          render: (h, params) => {
            let obj = this.mixinPaserStatus(params.row.status);
            return h(
              'span',
              {
                style: {
                  color: obj.color,
                  width: '90px',
                  display: 'inline-block'
                }
              },
              obj.text
            );
          }
        },
        {
          title: '审批信息',
          key: 'approvalInfo',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '危险等级',
          key: 'level',
          width: 100,
          tooltip: true,
          render: (h, params) => {
            let obj = this.mixinPaserLevel(params.row.level);
            return h(
              'span',
              {
                style: {
                  color: obj.color
                }
              },
              obj.text
            );
          }
        },
        {
          title: '危害程度',
          key: 'attackLevelName',
          align: 'center',
          width: 150,
          tooltip: true
        },
        {
          title: '分值',
          key: 'score',
          align: 'center',
          width: 80,
          tooltip: true
        },
        // {
        //   title: '防守方扣分',
        //   key: 'score1',
        //   align: 'center',
        //   width: 80,
        //   tooltip: true,
        //   render: (h, params) => {
        //     return h('span', params.row.type !== 2 ? params.row.score : '');
        //   }
        // },
        // {
        //   title: '防守方得分',
        //   key: 'score2',
        //   align: 'center',
        //   width: 80,
        //   tooltip: true,
        //   render: (h, params) => {
        //     return h('span', params.row.type === 2 ? params.row.score : '');
        //   }
        // },
        {
          title: '审批人',
          key: 'userName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '审批时间',
          key: 'approvalTime',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '操作',
          align: 'center',
          placement: 'top-right',
          key:'action',
          width:240,
          fixed:'right',
          opList:[
              {
                txt:'单位报告树',
                show:() => [1,2,3].includes(this.hwType),
                fun:(data) => {
                  this.reportTreeModal.company = data.company
                  this.reportTreeModal.show = true
                }
              },
              {
                  txt:'防御报告',
                  show:(data) => data.type === 1 && this.hwType != 2,
                  on:{
                      click:(data)=>{
                          this.getFileList(data, 0); // 展示关联的防御报告
                      }
                  }
              },
              {
                  txt:(data) => data.type === 1 ? '攻击报告' : '防御报告',
                  on:{
                      click:(data)=>{
                          this.getFileList(data, 1); // 展示当前报告
                      }
                    }
              }
          ],
          // render: (h, params) => {
          //   return h(
          //     'div',
          //     {
          //       style: {
          //         width: '150px'
          //       }
          //     },
          //     [
          //       h(
          //         'Button',
          //         {
          //           props: {
          //             type: 'primary',
          //             size: 'small'
          //           },
          //           style: {
          //             marginRight: '5px',
          //             display: params.row.type === 1 ? 'inline-block' : 'none'
          //           },
          //           on: {
          //             click: () => {
          //               this.getFileList(params.row, 0); // 展示关联的防御报告
          //             }
          //           }
          //         },
          //         '防御报告'
          //       ),
          //       h(
          //         'Button',
          //         {
          //           props: {
          //             type: 'primary',
          //             size: 'small'
          //           },
          //           style: {
          //             marginRight: '5px'
          //           },
          //           on: {
          //             click: () => {
          //               this.getFileList(params.row, 1); // 展示当前报告
          //             }
          //           }
          //         },
          //         params.row.type === 1 ? '攻击报告' : '防御报告'
          //       )
          //     ]
          //   );
          // }
        }
      ],
      reportInitObj: {
        Button: [],
        Input: [],
        Select: [],
        loading:false,
        showLoading:false,
        DatePicker: {
          isShow: false,
          fnName: d
        },
        Page: {
          total: 0,
          currentPage: 1,
          pageSize: 10
        },
        Table: {
          listCol: [
            {
              title: '名称',
              key: 'name',
              align: 'center',
              ellipsis: true,
              tooltip: true,
              placement: 'top-left',
              width: 240
            },
            {
              title: '提交人',
              key: 'creatorName',
              align: 'center',
              ellipsis: true,
              tooltip: true,
              width: 120
            },
            {
              title: '操作',
              align: 'center',
              key: 'active1',
              placement: 'top-right',
              action: true,
              render: (h, params) => {
                return h('div', [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'primary',
                        size: 'small'
                      },
                      style: {
                        marginRight: '5px'
                      },
                      on: {
                        click: () => {
                          //this.downloadFile(params.row);
                        }
                      }
                    },
                    [
                      h(
                        'a',
                        {
                          attrs: {
                            href: `/api/minio/download/${params.row.id}`
                          },
                          style: {
                            color: '#fff'
                          }
                        },
                        '下载'
                      )
                    ]
                  ),
                  h(
                    'Button',
                    {
                      props: {
                        type: 'primary',
                        size: 'small'
                      },
                      style: {
                        marginRight: '5px'
                      },
                      on: {
                        click: () => {
                          //新的预览接口
                          window.open(`/api/minio/filePreview?id=${params.row.id}`);
                        }
                      }
                    },
                    '预览'
                  )
                ]);
              }
            }
          ]
        },
        listData: []
      },
      timeout: {},
      industryList: [],
      attackList: [],
      extent4InjuryData: [],
      extent4DefenseTypesData: [],
      ruleList: [],
      companyList: []
    };
  },
  computed: {
    filterTeamList() {
      return this.teamList.filter((item) => item.name !== '目标方管理员组');
    },
    hwType(){
      let extension = JSON.parse(this.drillDetail.extension)
      return extension.hwType
    }
  },
  watch: {},
  created() {},
  beforeDestroy() {
    clearTimeout(this.timeout);
  },
  async mounted() {
    // await this.getIndustryTypes();
    // await this.getAttackTypes();
    // await this.getHwAttackLevelTypes();
    // await this.getHwDefenseTypes();
    await this.queryHWScoreRule();
    this.getRankingStatic();
    this.getTopoTargetList();
    this.getDeclareCompanyList();
    this.getTaskList()
  },
  methods: {
    changeSize(val) {
      this.queryParams.pageSize = val
      this.getRankingStatic(1)
    },
    getTaskList(){
        getTaskList({
          testId: this.$route.query.id,
          taskMode:'preset',

        }).then((response)=>{
            if(response.code==1){
                this.taskList = response.data.items.filter(item=>item.taskType==='loop_report');
            }else if(response.code==-2){
                
            }else{
                $this.$Message.error(response.message)
            }
        })
    },
    // 显示外网IP绑定模态框
    showUploadModal() {
      this.$refs.submitReportModal.openModal();
    },
    // 级联选择只展示叶子节点的内容
    renderFormat(label) {
      return label[label.length - 1];
    },
    // 获取目标危害程度
    getHwAttackLevelTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwAttackLevelTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.attackLevelList = list;
            let parentNodeList = list.filter((item) => item.parentid === '');
            this.extent4InjuryData = parentNodeList.map((item) => {
              let ret = {
                value: item.dictid,
                label: item.dictname,
                children: []
              };
              list.forEach((subItem) => {
                if (subItem.parentid === item.dictid) {
                  // 将二级的字典遍历查询出来
                  ret.children.push({
                    value: subItem.dictid,
                    label: subItem.dictname
                  });
                }
              });
              return ret;
            });
          })
          .catch(() => {
            this.$Message.error('获取目标危害程度列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 获取目标危害程度
    getHwDefenseTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwDefenseTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.defenseTypesList = list;
            let parentNodeList = list.filter((item) => item.parentid === '');
            this.extent4DefenseTypesData = parentNodeList.map((item) => {
              let ret = {
                value: item.dictid,
                label: item.dictname,
                children: []
              };
              list.forEach((subItem) => {
                if (subItem.parentid === item.dictid) {
                  // 将二级的字典遍历查询出来
                  ret.children.push({
                    value: subItem.dictid,
                    label: subItem.dictname
                  });
                }
              });
              return ret;
            });
          })
          .catch(() => {
            this.$Message.error('获取目标危害程度列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 获取行列列表
    getIndustryTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwIndustryTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.industryList = list;
          })
          .catch(() => {
            this.$Message.error('获取行业列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 获取攻击类型列表
    getAttackTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwAttackTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.attackList = list;
          })
          .catch(() => {
            this.$Message.error('获取攻击类型列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    getDeclareCompanyList() {
      getDeclareCompanyList(this.$route.query.prjid)
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.companyList = data;
          } else {
          }
        })
        .catch((error) => {});
    },
    getTopoTargetList() {
      getTopoTargetList({
        pageIndex: 1,
        pageSize: 2147483647,
        projectId: this.$route.query.prjid
      }).then((data) => {
        if (data.code == 1) {
          this.topoTargetData = data.data.items || data.data;
        } else {
          this.topoTargetData = [];
          this.$Message.warning(data.message);
        }
      });
    },
    queryHWScoreRule() {
      return new Promise((resolve, reject) => {
        let query = { pageIndex: 1, pageSize: 100000 };
        queryHWScoreRule(this.$route.query.id, query)
          .then(({ code, data, message }) => {
            if (code == 1) {
              this.ruleList = data.items;
              resolve();
            } else {
              this.$Message.error(message);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    getRankingStatic(page) {
      this.$nextTick(() => {
        page !== undefined && (this.queryParams.pageIndex = page); // page不为空时，将page赋值给pageIndex
        let {
          teamId,
          target,
          industry,
          attackType,
          level,
          isverify,
          pageIndex,
          pageSize,
          type,
          defenseTypes,
          publicTarget,
          attackLevel,
          company
        } = this.queryParams || {};
        let params = {
          page: pageIndex,
          pageSize,
          testId: this.$route.query.id,
          industry,
          attackType,
          level,
          company,
          status: isverify,
          target,
          groupId: teamId,
          type,
          defenseType: defenseTypes.length ? defenseTypes[defenseTypes.length - 1] : undefined,
          publicTarget: publicTarget ? publicTarget === '1' : undefined,
          attackLevel: attackLevel.length ? attackLevel[attackLevel.length - 1] : undefined
        };
        if (this.$route.query.id) {
          reportStatis(params).then((data) => {
            if (data.code == 1) {
              let list = data.data.pageData;
              this.retData.list = list.map((item) => {
                let rule = this.ruleList.find(
                  (rule) => rule.id === item.attackType || item.defenseType
                );
                item.attackTypeName = item.attackType && rule ? rule.category : '';
                item.attackLevelName = item.attackLevel;
                item.defenseTypeName = item.defenseType && rule ? rule.category : '';
                // item.attackTypeName = this.getValueByList(item.attackType, this.attackList);
                // item.industryName = this.getValueByList(item.industry, this.industryList);
                // item.attackLevelName = this.getValueName(item.attackLevel, this.attackLevelList);
                // item.defenseTypeName = this.getValueName(item.defenseType, this.defenseTypesList);
                return item;
              });
              this.retData.total = data.data.totalCount;
              if (this.poll) {
                //如果需要轮询
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                  this.getRankingStatic(page);
                }, 10000);
              }
            }
          });
        }
      });
    },
    // 递归获取级联选择框的数据
    getValueName(value, operatedList, list = []) {
      let item = operatedList.find((item) => item.dictid === value) || {};
      list.unshift(item.dictname);
      if (item.parentid) {
        this.getValueName(item.parentid, operatedList, list);
      }
      return list.join(' / ');
    },
    // 从列表中找出对应ID的名称，无法获取时返回ID
    getValueByList(id, list) {
      let item = list.find((item) => item.dictid === id);
      return item ? item.dictname : id;
    },
    // 将行业Id转换为对应的名称
    getIndustryName(industryId) {
      let item = this.industryList.find((item) => item.dictid === industryId);
      // 返回对应的名称，没有查到数据，还是返回ID
      return item ? item.dictname : industryId;
    },
    getFileList(item, type) {
      let _this = this;
      this.fileModal = true;
      this.defeFileList = [];
      reportFileData(item.id)
        .then((res) => {
          if (res.data.code === 1) {
            let attackStartTime = res.data.data.startTime;
            let attackEndTime = res.data.data.endTime;
            let reportName = res.data.data.reportName;
            let defeFileList = res.data.data.defenseFiles; // 防御报告
            let fileList = res.data.data.files; // 攻击报告
            if (type === 0) {
              _this.reportInitObj.Table.listData = defeFileList;
              this.modalTitle = '防御报告';
            } else {
              _this.reportInitObj.Table.listData = fileList;
              this.modalTitle = item.type === 1 ? '攻击报告' : '防御报告';
            }
            let connectRecords = res.data.data.connectRecords;
            this.reportModal = true;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    downloadFile(file) {
      downloadFile(file.id)
        .then((data) => {
          if (!data.code) {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = file.name;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error('下载报告失败!');
        });
    }
  }
};
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}
.targetHeader {
  padding: 10px;
  margin-bottom: 10px;
}
</style>
